$(function(){
    /**
     * Authorization handler. Window popup through ajax
     */
    $('.login-me').live('click',function(){
        var content = $('<div />').css('text-align','center').append('<img height="32" src="/images/preloader.gif" />');
        var D = $.dialog(content,'Вход на сайт',{
            callback:function(){
                var form = $(this).find('form');
                form.submit();
                return false;
            }
        });
        $.get('/user/login',function(m){
            var x = $(m);
            x.find('.save').remove();
            content.removeAttr('style').html(x);
            var form = content.find('form');
            form.submit(function(e){
                $.loader();
                $.post(form.attr('action'),form.serialize(),function(m){
                    $.loader();
                    if(m.status === 'OK'){
                        location.reload();
                    }else if(typeof m === 'object'){
                        var errs = form.find('.errors').css('display','block')
                        errs.html(m.message);
                    }else {
                        form.find('.errors').css('display','block').html('Ошибка на сервере!');
                    }
                },'json').error(function(){
                    form.find('.errors').css('display','block').html('Ошибка на сервере!');
                });
                return false;
            });
            content.find('input').keydown(function(e){
                if(e.keyCode == 13)
                    form.submit();
            });
            content.slideDown(function(){
                D.setRelativePosition(window);
            });
        }).error(function(){
            content.removeAttr('style').html('<b style="color:red">Ошибка на сервере. Обратитесь к администратору</b>');
        })
        return false;
    })
    /**
     * Feedback form. Window popup through ajax
     */
    $('.feedback-me').live('click',function(){
        var content = $('<div />').css('text-align','center').append('<img height="32" src="/images/preloader.gif" />');
        var D = $.dialog(content,'Оставить отзыв',{
            callback:function(){
                var form = $(this).find('form');
                if(typeof form[0] === 'undefined')
                    D.close();
                $.post(form.attr('action'),form.serialize(),function(m){
                    if(m.status === 'OK'){
                        $('<h2 />').css({'text-align':'center'}).html(m.message).insertAfter(form);
                        form.remove();
                        
                    }else if(typeof m === 'object'){
                        var errs = form.find('.errors').css('display','block')
                        errs.html($(m.message).removeClass('errors'));
                    }else {
                        form.find('.errors').css('display','block').html('Ошибка на сервере!');
                    }
                },'json').error(function(){
                    form.find('.errors').css('display','block').html('Ошибка на сервере!');
                });
                return false;
            }
        });
        $.get('/feedback/',function(m){
            var x = $(m);
            x.find('.save').remove();
            content.removeAttr('style').html(x);
            x.slideDown(function(){
                D.setRelativePosition(window);
            });
        }).error(function(){
            content.removeAttr('style').html('<b style="color:red">Ошибка на сервере. Обратитесь к администратору</b>');
        });
        return false;
    });
    var first_load = true;
    var current_href = null;
    var initial_location = location.href;
    var il = {html:$('body .main-block').html(),class:$('body .main-block').attr('class')};
    //no reload logic
    var main_frame = $('<iframe />').attr({'id':'main_frame','name':'main_frame'})
            .css({'width':'0','height':'0','position':'absolute','left':'-9999px'})
            .load(function(){
                var body = $(this).contents().find('body');
                var bg = body.css('background');
                $('body').css('background',bg)
                var content = body.find('.main-block');
                if(!first_load && typeof content[0] !== 'undefined'){
                    $.loader();
                    var chtml = content.html();
                    $('body .main-block').html(chtml).attr('class',content.attr('class'));
                    if(typeof admin_init === 'function')
                        admin_init();
                    findMusic();
                    var href = $(this).attr('src');
                    history.pushState({html:chtml,class:content.attr('class')}, current_href, current_href);
                    $(document).scrollTop(0);
                }else
                    first_load = false;
            });
    $('body').append(main_frame.removeAttr('src'));
    if(location.href.indexOf('/add')===-1)
    $('a[href^="/"]').live('click',function(e){
        if((/^\//).exec($(this).attr('href')) && $(this).attr('href').indexOf('/add')===-1){
            var href = $(this).attr('href');
            $.loader();
            main_frame.attr('src',href+'?x3_load_frame=1');
            current_href = href;
            e.preventDefault();
            e.stopImmediatePropagation();
            return false;
        }
    });
    
    window.onpopstate = function(e) {
        var returnLocation = history.location || document.location;
        if(current_href !=null){
            if(!$.rusWindows['@loader'])
                $.loader();
            main_frame.attr('src',returnLocation+'?x3_load_frame=1');
        }
        current_href = returnLocation;
        
        return true;
        var s = e.state;
        if(s && s.hasOwnProperty('html') && s.html !== ''){
            $('body .main-block').html(s.html).attr('class',s.class);
        }else if(returnLocation === initial_location) {
            $('body .main-block').html(il.html).attr('class',il.class);
        }
    };

    
    /**
     * Music player init
     */
    var myMusic = [];
    var mySound = null;
    var currentSong = -1;
    var playing = false;
    var playerui = null;
    if(typeof window.sm === 'undefined')
    window.sm = soundManager.setup({
        // required: path to directory containing SM2 SWF files
        url: './js/swf/',
        onready:function(){
            playerui = new init_music_ui();
            findMusic();
        }
    });
    function next_song(){
        currentSong++;
        if(currentSong !== myMusic.length){
            if(mySound !== null) {
                mySound.stop();
                mySound.destruct();
            }
            mySound = soundManager.createSound({
              id: 'aSound',
              url: myMusic[currentSong],
              finish:function(){
                    next_song();
              }
            });
            playerui && playerui.makeCurrent(currentSong);
            mySound.play();
            playing = true;
            if(playerui && playerui.button.hasClass('stop'))
                playerui.button.removeClass('stop')
        }else {
            if(mySound !== null){
                mySound.destruct();
                mySound = null;
            }
            playing = false;
            playerui && playerui.button.addClass('stop')
            currentSong = -1;
        }
    }
    function findMusic(){
        var added = 0;
        $('audio').each(function(i){
            var src = $(this).attr('src');
            var title = $(this).attr('title');
            if(myMusic.indexOf(src)===-1){
                !!playerui && playerui.addNote(myMusic.length,title);
                myMusic.push(src);
                added++;
            }
        });
        notifyNewMusic(added);
    }
    function notifyNewMusic(cnt){
        if(cnt>0){
            //autostart new added tracks
            if(!playing){
                next_song();
            }
            //TODO: show number of new added tracks
        }
    }
    
    function init_music_ui(){
        var self = this;
        this.button = $('<div />').attr({'title':'Проиграть'}).addClass('play_pause stop').click(function(){
                if(myMusic.length == 0)
                    return false;
                $(this).toggleClass('stop');
                if(playing){
                    //TODO:remember my choise
                    mySound.pause();
                    playing = false;
                    $(this).attr('title','Проиграть');
                }else{
                    mySound.play();
                    playing = true;
                    $(this).attr('title','Остановить');
                }
            });
        this.ui = $('<div />').addClass('music_bg').append(this.button);
        this.notes = $('<div />').addClass('notes_holder');
        this.addNote = function(i,title){
            var anima = $('<div />').addClass('anima');
            this.notes.append($('<div />').addClass('note').attr({'title':title}).data('im',i).click(function(){
                if($(this).hasClass('current')){
                    self.button.click();
                    return false;
                }
                currentSong = $(this).data('im')*1 - 1;
                next_song();
            }).append('<img src="/images/note.png" />').append(anima));
            anima.animate({'opacity':'0','zoom':'20','top':'-20px'},500,function(){$(this).remove();});
        };
        this.makeCurrent = function(i){
            this.notes.children('.note.current').removeClass('current');
            this.notes.children('.note').eq(i).addClass('current');
        }
        $('body').append(this.ui).append(this.notes);
        return this;
    }
})